/*
 @Name: navbar插件
 @Author: ray
 @License: MIT
 */
; rayui.define(function (exports, undef) {
    "use strict";

    var $ = rayui.$,
        $doc = $(document),
        plugName = "navbar",
        globalIndex = 1000,
        dataCache = {},
        scrollGap = null,
        //只运行一次
        initDefaultOnce= function () {
            //计算浏览横向滚动条的高度和竖向滚动条的宽度
            if (scrollGap != null) return;
            scrollGap = {};
            var $div = $("<div/>").appendTo($("body"));
            $div.width(100).height(100).css("overflow", "scroll");
            var elem = $div[0];
            scrollGap.width = elem.offsetHeight - elem.clientHeight;
            scrollGap.height = elem.offsetWidth - elem.clientWidth;
            $div.remove();
        },
        DealClass = function (options) {
            //判断是否已经渲染
            var index = $(options.elem).data("index");
            if (index > 0) 
                delete dataCache[index];

            options.index = globalIndex;
            $(options.elem).data("index", globalIndex);
            options = this.options = $.extend({}, DealClass.option, options);
            !$.isArray(options.data) && (options.data = []);

            //初始化
            options.exists ? DealClass.utils.initExists.call(this)
                : options.isLand ? DealClass.utils.initLandscape.call(this) : DealClass.utils.initVertical.call(this);
            DealClass.utils.renderData.call(this);
            DealClass.utils.event.call(this);
            return this;
        };

    DealClass.option = {
        isLand: true,//true横向 false竖向
        fieldId: "id", //数据列
        fieldName: "name", //显示列
        fieldChildren: "children", //子节点
        toLevel: 100,//渲染级别，从0开始，使用此属性可以实现两个菜单级联
        titleSpread: true,//点击标题展开
        indent: false,//级别缩进，默认无缩进
        spreadFirst: false,//展开第一个
        spreadOnly: true, //统一级别只展开一个
        animSpeed: 200//动画执行时间
    };

    DealClass.utils = {
        //横向
        initLandscape: function () {
            var that = this,
                options = that.options;

            options.$elem = $(options.elem).addClass("rayui-nav nav-land").html('');
            options.$ul = $('<ul/>').appendTo(options.$elem);
            options.skin && options.$elem.attr("skin", options.skin);
            options.bgColor && options.$elem.css("background-color", options.bgColor);
        },
        //竖向
        initVertical: function () {
            var that = this,
                options = that.options;

            options.$elem = $(options.elem).addClass("rayui-nav nav-vert").html('');
            options.$noscroll = $('<div class="rayui-noscroll" />').appendTo(options.$elem);
            options.$ul = $('<ul/>').appendTo(options.$noscroll);
            options.skin && options.$elem.attr("skin", options.skin);
            options.bgColor && options.$elem.css("background-color", options.bgColor);
            options.indent && options.$elem.addClass("nav-indent");
            //隐藏竖向滚动条
            initDefaultOnce();
            options.$noscroll.outerWidth(options.$elem.outerWidth() + scrollGap.width);
            options.$ul.outerWidth(options.$ul.outerWidth() - scrollGap.width);
        },
        initExists: function () {
            var that = this,
                options = that.options;

            options.$elem = $(options.elem);
            options.$ul = options.$elem.find('>ul');
            if (options.$elem.hasClass("nav-vert")) {
                options.isLand = false;
                options.$noscroll = $('<div class="rayui-noscroll" />').append(options.$ul).appendTo(options.$elem);
                //隐藏竖向滚动条
                initDefaultOnce();
                options.$noscroll.outerWidth(options.$elem.outerWidth() + scrollGap.width);
                options.$ul.outerWidth(options.$ul.outerWidth() - scrollGap.width);
            } else {
                options.isLand = true;
                options.$elem.addClass("nav-land");
            }

            //计算层级
            var calcLevel = function($ul, level) {
                $ul.find('>li>ul').each(function() {
                    $(this).attr("iteration", level + 1);
                    calcLevel($(this), level + 1);
                });
            };
            calcLevel(options.$ul, 0);
            //添加折叠按钮
            options.$ul.find('li').each(function() {
                if($(this).find('>ul').length>0)
                    $(this).find('>a').append('<span class="btn-nav-spread"><i class="ra ra-arrow-down"></i></span>');
            });
        },
        renderData: function () {
            var that = this,
                options = that.options;
            
            //添加数据
            var addRow = function (data, $parent, iteration, preindex) {
                preindex = preindex || "";
                $(data).each(function (a, b) {
                    var li = [],
                        hasChildren = b.hasOwnProperty(options.fieldChildren) && b[options.fieldChildren].length > 0;
                    
                    li.push('<li data-index=[' + preindex + a + ']');
                    options.fieldId && li.push(' data-id=' + b[options.fieldId]);
                    li.push(' class="');
                    options.spreadFirst && iteration === 0 && hasChildren && a === 0 && li.push('rayui-spread');
                    li.push('"');//end class
                    li.push('>');
                    
                    //数据a标签<a href="javascript:"><i class="ra ra-file"></i>菜单1菜单1菜单1菜单1菜单1菜单1菜单1</a>
                    li.push('<a href="javascript:"');
                    li.push(' class="');
                    b.disabled && li.push('rayui-disabled');//是否禁用
                    li.push('">');//end class

                    if (typeof options.format === "function") {
                        li.push(options.format(b, data)||"");
                    } else {
                        //添加图标
                        if (typeof b.icon === "string") {
                            if (b.icon.indexOf('fa-') === 0) {
                                li.push('<i class="fa ' + b.icon + '" aria-hidden="true"></i>');
                            } else if (b.icon.indexOf('ra-') === 0) {
                                li.push('<i class="ra ' + b.icon + '" aria-hidden="true"></i>');
                            } else {
                                li.push('<img src="' + b.icon + '" alt=""/>');
                            }
                        }

                        li.push('<span class="tree-title">' + b[options.fieldName] + '</span>');
                        li.push('</a></li>');
                    }
                    var strHtml = li.join('');
                    var $li = $("" + strHtml);
                    $li.appendTo($parent);
                    
                    if (hasChildren && iteration < options.toLevel) {
                        //添加折叠按钮
                        $li.find('>a').append('<span class="btn-nav-spread"><i class="ra ra-arrow-down"></i></span>');
                        var $innerUl = $('<ul iteration=' + (iteration + 1) +'/>').appendTo($li);
                        addRow(b[options.fieldChildren], $innerUl, iteration + 1, preindex + a + ",");
                    }
                });
            }

            addRow(options.data, options.$ul, 0);
        },
        event: function () {
            var that = this,
                options = that.options,
                getData = function (indexes) {
                    var datas = options.data;
                    if (indexes === undef) return datas;
                    var count = indexes.length,
                        i = 1,
                        data = datas[indexes[0]];
                    while (i < count)
                        data = data[options.fieldChildren][indexes[i++]];
                    return data;
                };

            //折叠展开
            options.$ul.on("click.spread" + plugName, 'a:not(.rayui-disabled)>.btn-nav-spread', function (e) {
                e.stopPropagation();
                var $li = $(this).closest('li'), $ul = $li.find('>ul'),
                    isSpread = $li.hasClass('rayui-spread');
                if (isSpread) {
                    //折叠
                    $ul.slideUp(options.animSpeed, function () {
                        $ul.css("display", "");
                        $li.removeClass('rayui-spread');
                    });
                } else {
                    //展开
                    if (options.spreadOnly) {
                        var $pli = $(this).parents('li').last();
                        options.$ul.find("li.rayui-spread").not($pli).find('.btn-nav-spread').click();
                    }
                    $ul.slideDown(options.animSpeed, function () {
                        $ul.css("display", "");
                        $li.addClass('rayui-spread');
                    });
                }
            });

            //点击事件
            options.$ul.on("click." + plugName, 'a:not(.rayui-disabled)', function (e) {
                var $btnSpread = $(this).find('.btn-nav-spread');
                //点击标题展开
                if ($btnSpread.length > 0) {
                    options.titleSpread && $btnSpread.click();
                    options.isLand && e.stopPropagation();
                    return;
                }
                //选中
                var $preActive = options.$ul.find('a.rayui-active');
                $preActive.removeClass("rayui-active");
                $(this).addClass("rayui-active");
                //如果是横向点击后折叠
                if (options.isLand) {
                    $preActive.parents('li').last().removeClass("rayui-root-active");
                    var $pli = $(this).parents('li').last().addClass("rayui-root-active");
                    $pli.find('.btn-nav-spread').click();
                }
                typeof options.onClick === "function" && options.onClick.call(this, getData($(this).closest('li').data("index")));
            });
        }
    }
    
    //点击空白隐藏横向
    $doc.on("click." + plugName, function() {
        $(".nav-land>ul>li.rayui-spread>a>.btn-nav-spread").click();
    });
    
    var handler = {
        options: DealClass.option,
        render: function (options) {
            (typeof options === "string" || options instanceof jQuery) && (options = { elem: options });
            if ($(options.elem).length === 0) return "DOM对象不存在";
            var classObj = new DealClass(options);
            dataCache[globalIndex++] = classObj;
            return classObj;
        }
    };

    $(function() {
        $(".rayui-nav").each(function() {
            handler.render({
                elem: $(this),
                exists: true
            });
        });
    });


    exports(plugName, handler);
}, rayui.jsAsync());
